import time
import utils
import pandas as pd
import os
from docx import Document
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH #设置对象居中、对齐等。
from docx.enum.text import WD_TAB_ALIGNMENT,WD_TAB_LEADER #设置制表符等
from docx.enum.text import WD_UNDERLINE
from docx.enum.text import WD_TAB_ALIGNMENT
from docx.enum.text import WD_LINE_SPACING
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.enum.table import WD_ROW_HEIGHT_RULE
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import Inches #设置图像大小
from docx.shared import Cm
from docx.shared import Pt #设置像素、缩进等
from docx.shared import RGBColor #设置字体颜色
from docx.shared import Length #设置宽度
from docx.shared import Inches  # 设置图像大小

def docx_add_table(doc:Document,df:pd.DataFrame,ColWidthList:tuple=(),title = True):
    # 初始化行数，列数，以及循环写入表格数据的初始行
    row_count = df.shape[0]
    first_row = 0
    column_count = df.shape[1]
    # 如果包含标题，则总行数和循环起始行+1
    if title:
        row_count = row_count+1
        first_row = first_row +1
    column_count = df.shape[1]
    
    # 根据dataframe的shape创建空列表，多出标题行
    table0 = doc.add_table(rows=row_count, cols=column_count)
    table0.autofit = True
    # 居中
    table0.alignment = WD_TABLE_ALIGNMENT.CENTER
    if len(ColWidthList) == column_count:
        for m in range(row_count):
            for n in range(column_count):
                table0.cell(m, n).width = Cm(ColWidthList[n])
    
    # 写表头
    for i in range(column_count):
        cell = table0.cell(0, i)
        p = cell.paragraphs[0]
        run = p.add_run(df.columns[i])
        run.bold = True

    # 写表本体
    for x in range(0, df.shape[0]):
        for y in range(column_count):
            table0.rows[first_row+x].cells[y].text = str(df.iloc[x, y])

def docx_add_heading(doc:Document,text:str,paragraph_format:tuple=(5,5,0),heading_class:int=1,color:tuple=(0,0,0)):
    heading0 = doc.add_heading("",1)
    heading0.paragraph_format.space_after = Pt(paragraph_format[0])
    heading0.paragraph_format.space_before = Pt(paragraph_format[1])
    heading0.paragraph_format.line_spacing = Pt(paragraph_format[2])
    heading0_run = heading0.add_run(text)
    heading0_run.font.color.rgb = RGBColor(color[0],color[1],color[2])
    
if __name__ == '__main__':
    
    df = pd.DataFrame(data=[['1', '2', '3'], ['4', '5', '6']], columns=['A', 'B', 'C'])
    
    productinfo = {"Product Code": df.iloc[0, 0],
                "Product Name": df.iloc[0, 1],
                'Document type': "Nutrition Facts",
                "Doc date": time.strftime("%b %Y", time.localtime())}
           
    header_template = utils.generate_Header(productinfo)
    doc = Document(header_template)
    
    
    docx_add_table(doc,df,ColWidthList=[0.5,1,1])
    
    save_path = utils.set_save_path(productinfo)
    filename = os.path.join(save_path, os.path.split(header_template)[-1])
    doc.save(filename)